package pers.jl.controller;


import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import pers.jl.common.R;
import pers.jl.entity.AddressBook;
import pers.jl.service.IAddressBookService;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * <p>
 * 地址管理 前端控制器
 * </p>
 *
 * @author luge
 * @since 2023-04-22
 */
@RestController
@RequestMapping("/addressBook")
@Slf4j
public class AddressBookController {

    @Autowired
    private IAddressBookService addressBookService;

    /**
     * 用户新增地址
     * @param address
     * @return
     */
    @PostMapping
    public R saveAddressBook(HttpSession session, @RequestBody AddressBook address){
        // 新增地址簿
        addressBookService.saveAddress(session,address);
        return R.success("新增地址成功！");
    }

    /**
     * 查询当前用户所有地址信息
     * @return
     */
    @GetMapping("/list")
    public R<List<AddressBook>> getAll(HttpSession session){
        // 查出所有地址信息的集合
        List<AddressBook> addressBookList = addressBookService.getAllAddress(session);
        return R.success(addressBookList);
    }

    /**
     * 修改地址簿
     * @param address
     * @return
     */
    @PutMapping
    public R updateAddressBook(@RequestBody AddressBook address){
        addressBookService.updateAddress(address);
        return R.success("地址修改成功！");
    }

    /**
     * 修改地址时，数据回显
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<AddressBook> getBackAddress(@PathVariable Long id){
        // 传入地址id,修改地址簿时数据回显
        AddressBook addressBook = addressBookService.getByAddressId(id);
        return R.success(addressBook);
    }

    /**
     * 设置为默认地址
     * @param address
     * @return
     */
    @PutMapping("/default")
    public R changeToDefault(@RequestBody AddressBook address,HttpSession session){
        addressBookService.change(address,session);
        return R.success("已设置为默认地址。");
    }

    /**
     * 删除地址
     * @param ids
     * @return
     */
    @DeleteMapping
    public R deleteAddress(String ids){
        addressBookService.deleteAddressBook(ids);
        return R.success("地址删除成功！");
    }

    /**
     * 查询默认地址
     * @return
     */
    @GetMapping("/default")
    public R getDefault(){
        AddressBook defaultAddress = addressBookService.getDefaultAddress();
        return R.success(defaultAddress);
    }

}
